// 获取Aes加密
// npm i aes-js
// import CryptoJS from "crypto-js";

let aes = require('aes-js');

/**
 * @FileName: AesUtil
 * @Author: mazaiting
 * @Date: 2018/7/5
 * @Description: AES加密工具类，使用方法
 *  加密
 *  let encrypted = AesUtil.encrypt("mazaiting");
 *  解密
 *  let decrypted = AesUtil.decrypt("mazaiting");
 */
class AesUtil {
    /**
     * 设置KEY
     * @param key 密钥
     */
    static key(key) {
        if (key.length / 16 !== 0) {
            console.warn("密钥无效...")
        }
        _key = key;
    }

    /**
     * iv设置无效
     * @param iv iv
     */
    static iv(iv) {
        if (iv.length / 16 !== 0) {
            console.warn("密钥无效...")
        }
        _iv = iv;
    }

    /**
     * 加密
     * @param text 加密文本
     */
    static encrypt(text) {
        // 将文本转换为字节 - Convert text to bytes
        let textBytes = aes.utils.utf8.toBytes(text);
        // 设置加密模式为 - ofb    ( Output Feedback )
        let aesOfb = new aes.ModeOfOperation.ofb(_key, _iv);
        // 加密数据
        let encryptedBytes = aesOfb.encrypt(textBytes);
        // 将二进制转换为16进制数据 - To print or store the binary data, you may convert it to hex
        return aes.utils.hex.fromBytes(encryptedBytes);
    }

    /**
     * 解密
     * @param text 待解密文本
     */
    static decrypt(text) {
        // 将文本转换为字节 - When ready to decrypt the hex string, convert it back to bytes
        let encryptedBytes = aes.utils.hex.toBytes(text);
        // 设置 解密模式
        // The output feedback mode of operation maintains internal state,
        // so to decrypt a new instance must be instantiated.
        let aesOfb = new aes.ModeOfOperation.ofb(_key, _iv);
        // 解密数据
        let decryptedBytes = aesOfb.decrypt(encryptedBytes);
        // 将字节数据转换为字符串 - Convert our bytes back into text
        return aes.utils.utf8.fromBytes(decryptedBytes);
    }



}


/**
 * 导出当前Module
 */
module.exports = AesUtil;